package com.qkun.library.views;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatImageView;

import com.qkun.library.utils.DrawableUtils;
import com.qkun.library.utils.Utils;

/**
 * @author qinkun
 * @date 12/7 0007 21:33
 * @description
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class FlipCardView extends FrameLayout {

    private AppCompatImageView mForegroundImageCardView;
    private AppCompatImageView mBackgroundImageCardView;

    private AnimatorSet mRightOutAnimatorSet;
    private AnimatorSet mLeftInAnimatorSet;

    private boolean mShowBackgroundImage;
    private Drawable mForeground;

    public FlipCardView(@NonNull Context context) {
        this(context, null);
    }

    public FlipCardView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs, 0);
    }

    public FlipCardView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public FlipCardView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    private void init() {
        mForeground = DrawableUtils.getDrawableOfSelectableItemBackground(false);
        setForeground(mForeground);
        // TODO: 12/7 0007 要确保两张图片大小一样
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

        mBackgroundImageCardView = new AppCompatImageView(getContext());
        mBackgroundImageCardView.setAdjustViewBounds(true);
        addView(mBackgroundImageCardView, layoutParams);

        mForegroundImageCardView = new AppCompatImageView(getContext());
        mForegroundImageCardView.setAdjustViewBounds(true);
        addView(mForegroundImageCardView, layoutParams);

        setCameraDistance();
    }

    /**
     * 涉及到旋转卡片的Y轴, 即rotationY, 需要修改视角距离.如果不修改, 则会超出屏幕高度, 影响视觉体验
     */
    private void setCameraDistance() {
        float scale = getResources().getDisplayMetrics().density * 16000/*distance*/;
        mForegroundImageCardView.setCameraDistance(scale);
        mBackgroundImageCardView.setCameraDistance(scale);
    }

    private void setupFlipAnimator() {
        final int duration = 360;
        //右出动画
        ObjectAnimator outRotationYAnimator = new ObjectAnimator();
        outRotationYAnimator.setProperty(View.ROTATION_Y);
        outRotationYAnimator.setFloatValues(0.0f, 180.0f);
        outRotationYAnimator.setDuration(duration);

        ObjectAnimator outAlphaAnimator = new ObjectAnimator();
        outAlphaAnimator.setProperty(View.ALPHA);
        outAlphaAnimator.setFloatValues(1.0f, 0.0f);
        outAlphaAnimator.setDuration(0);
        outAlphaAnimator.setStartDelay(duration >> 1);

        mRightOutAnimatorSet = new AnimatorSet();
        mRightOutAnimatorSet.play(outRotationYAnimator).with(outAlphaAnimator);

        //左进动画
        ObjectAnimator inOutAlphaAnimator = new ObjectAnimator();
        inOutAlphaAnimator.setProperty(View.ALPHA);
        inOutAlphaAnimator.setFloatValues(1.0f, 0.0f);
        inOutAlphaAnimator.setDuration(0);

        ObjectAnimator inRotationYAnimator = new ObjectAnimator();
        inRotationYAnimator.setProperty(View.ROTATION_Y);
        inRotationYAnimator.setFloatValues(-180.0f, 0.0f);
        inRotationYAnimator.setDuration(duration);

        ObjectAnimator inAlphaAnimator = new ObjectAnimator();
        inAlphaAnimator.setProperty(View.ALPHA);
        inAlphaAnimator.setFloatValues(0.0f, 1.0f);
        inAlphaAnimator.setDuration(0);
        inAlphaAnimator.setStartDelay(duration >> 1);

        mLeftInAnimatorSet = new AnimatorSet();
        mLeftInAnimatorSet.play(inOutAlphaAnimator).with(inRotationYAnimator).with(inAlphaAnimator);

        mRightOutAnimatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
                setForeground(null);
            }
        });
        mLeftInAnimatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                setForeground(mForeground);
            }
        });
    }

    public boolean isShowBackgroundImage() {
        return mShowBackgroundImage;
    }

    public void startFlipCardAnim(AnimatorListenerAdapter animatorListener) {
        if ((Utils.nonNull(mRightOutAnimatorSet) && mRightOutAnimatorSet.isRunning())
                || (Utils.nonNull(mLeftInAnimatorSet) && mLeftInAnimatorSet.isRunning())) {
            return;
        }
        //0是隐藏，1是显示
        final View[] target = new View[2];
        if (mShowBackgroundImage) {
            // 正面朝上
            mShowBackgroundImage = false;
            target[0] = mBackgroundImageCardView;
            target[1] = mForegroundImageCardView;
        } else {
            // 背面朝上
            mShowBackgroundImage = true;
            target[0] = mForegroundImageCardView;
            target[1] = mBackgroundImageCardView;
        }

        setupFlipAnimator();
        mRightOutAnimatorSet.setTarget(target[0]);
        mLeftInAnimatorSet.setTarget(target[1]);
        if (Utils.nonNull(animatorListener)) mLeftInAnimatorSet.addListener(animatorListener);
        mRightOutAnimatorSet.start();
        mLeftInAnimatorSet.start();
    }

    public void setImageResource(@DrawableRes int foregroundResId, @DrawableRes int backgroundResId) {
        mForegroundImageCardView.setImageResource(foregroundResId);
        mBackgroundImageCardView.setImageResource(backgroundResId);
    }

    public void updateForegroundImageResource(@DrawableRes int foregroundResId) {
        mForegroundImageCardView.setImageResource(foregroundResId);
    }

}
